/**
 * Copyright (c) 2002-2011 旭鸣信息
 * All rights reserved. 
 * File：DistributeRegionDaoImpl.java
 * History:
 *       May 11, 2012: Initially created, liuzhi.
 */
package com.xteam.ecsystem.dao.Impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xteam.ecsystem.dao.IDistributeRegionDao;
import com.xteam.ecsystem.entities.BaseAgentInfo;
import com.xteam.ecsystem.entities.BaseDistributeRegion;
import com.xteam.ecsystem.entities.BaseReceiveAddress;

/**
 * 商品分类数据访问实现类
 * 
 * @author liuzhi
 * 
 */
@Repository
public class DistributeRegionDaoImpl extends DDLPrefix implements
		IDistributeRegionDao {

	@SuppressWarnings("unchecked")
	@Autowired
	private BaseDaoImpl baseDao;

	@SuppressWarnings("unchecked")
	public void delObject(String id) {
		List list = new ArrayList();
		String hql = "";
		
		try {
			hql = SQL_FROM + BaseDistributeRegion.REF + SQL_WHERE + "bdrParent = ?";
			list = this.baseDao.find(hql, new Object[]{id});
			
			if (list != null && !list.isEmpty()) {
				for (int i = 0; i < list.size(); i++) {
					BaseDistributeRegion bdr = (BaseDistributeRegion)list.get(i);
					delObject(bdr.getBdrId());
				}
			}
			
			hql = SQL_DELETE + SQL_FROM + BaseDistributeRegion.REF + SQL_WHERE + "bdrId = ?";
			this.baseDao.executeUpdate(hql, new Object[]{id});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	public String getBdrInfoById(String id) {
		JSONObject jo = new JSONObject();
		List list = new ArrayList();
		try {
			String hql = SQL_FROM + BaseDistributeRegion.REF + SQL_WHERE + " 1=1 "
					+ SQL_AND + " bdrId=?";
			list = this.baseDao.find(hql, new Object[] {id});
			
			if(list != null && list.size() > 0){
				jo = JSONObject.fromObject((BaseDistributeRegion) list.get(0));
				return jo.toString();
			}
			

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "";
	}

	public String getBdrList(int pageIndex, int pageSize, String bdrName) {
		return null;
	}

	@SuppressWarnings("unchecked")
	public String lazyLoadRegionTree(String bdrParent) {
		if (bdrParent == null || "".equals(bdrParent)
				|| "null".equals(bdrParent) || "undefined".equals(bdrParent)) {
			bdrParent = "0"; 
		}
		
		List bdrTreeList = new ArrayList(); 

		//获取下一级节点
		String hql = SQL_FROM + BaseDistributeRegion.REF + SQL_WHERE + " bdrParent=? ";
		ArrayList list = (ArrayList)this.baseDao.find(hql, new Object[]{bdrParent});
		
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map = new HashMap<String, Object>();
				BaseDistributeRegion bdr = (BaseDistributeRegion)list.get(i);
				
				map.put("bdrId", bdr.getBdrId());
				map.put("bdrParent", bdr.getBdrParent());
				map.put("bdrName", bdr.getBdrName());
				bdrTreeList.add(map);
			}
		}
		
		// 判断节点，是否有子节点。如果有，则处理isLeaf和expanded。
		for (int i = 0, j = bdrTreeList.size(); i < j; i++) {
			HashMap node = (HashMap) bdrTreeList.get(i);
			String nodeId = node.get("bdrId").toString();

			String hql2 = SQL_FROM + BaseDistributeRegion.REF + SQL_WHERE	+ " bdrParent=? ";
			ArrayList nodeList = (ArrayList) this.baseDao.find(hql2, new Object[] { nodeId });

			if (nodeList != null && nodeList.size() > 0) {
				node.put("isLeaf", false);
				node.put("expanded", false);
			}
		}

		// 返回处理结果
		String bdrTree = PluSoft.Utils.JSON.Encode(bdrTreeList);
		return bdrTree;
	}

	@SuppressWarnings("unchecked")
	public String lazyLoadRegionTreeGrid(String bdrParent) {
		if (bdrParent == null || "".equals(bdrParent)
				|| "null".equals(bdrParent) || "undefined".equals(bdrParent)) {
			bdrParent = "0"; 
		}

		String sql = SQL_SELECT + " bdr.bdr_id as bdrId,bdr.bdr_parent as bdrParent,"
		 	    + "bdr.bdr_name as bdrName,bdr.bdr_type as bdrType,bdr.bdr_agent as bdrAgent," 
		 	    + "bdr.bdr_state as bdrState,bai.bai_name as baiName" + SQL_FROM 
		 	    + " base_distribute_region as bdr "
				+ " left join base_agent_info as bai on bdr.bdr_agent = bai.bai_id " + SQL_WHERE 
				+ " bdr.bdr_parent = ? "; 
		
		//返回map类型的ArrayList可以直接被PluSoft解析
		ArrayList bdrTreeList = (ArrayList)this.baseDao.queryWithSQL(Map.class,
				sql, new Object[]{bdrParent});

		// 判断节点，是否有子节点。如果有，则处理isLeaf和expanded。
		for (int i = 0, j = bdrTreeList.size(); i < j; i++) {
			HashMap node = (HashMap) bdrTreeList.get(i);
			String nodeId = node.get("bdrId").toString();

			String hql2_2 = SQL_FROM + BaseDistributeRegion.REF + SQL_WHERE	+ " bdrParent=? ";
			ArrayList nodeList = (ArrayList) this.baseDao.find(hql2_2, new Object[] {nodeId});

			if (nodeList != null && nodeList.size() > 0) {
				node.put("isLeaf", false);
				node.put("expanded", false);
			}
		}

		// 返回处理结果
		String bdrTree = PluSoft.Utils.JSON.Encode(bdrTreeList);
		return bdrTree;
	}

	public void saveOrUpdateObject(Object obj, String id) {
		try {
			BaseDistributeRegion bdr = (BaseDistributeRegion) obj;
			if (id != null && !id.equals("") && id.length() > 0) {
				this.baseDao.update(bdr);
			} else {
				this.baseDao.save(bdr);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	public void updateBdrStateById(String id) {
		Class clazz = null;
		try {
			clazz = Class.forName("com.xteam.ecsystem.entities.BaseDistributeRegion");

			BaseDistributeRegion bdr = (BaseDistributeRegion) this.baseDao.get(clazz,id);
			if (bdr.getBdrState() == 1) {
				bdr.setBdrState(0);
			} else {
				bdr.setBdrState(1);
			}

			this.baseDao.saveOrUpdate(bdr);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	public String getBaiListCob() {
		JSONArray ja = new JSONArray();
		List list = new ArrayList();
		try {
			String hql = SQL_FROM + BaseAgentInfo.REF + SQL_WHERE +" 1=1 " 
					+ SQL_AND + " baiState=1";
			list = this.baseDao.find(hql);
			
			ja = JSONArray.fromObject(list);

		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return ja.toString();
	}
	
	@SuppressWarnings("unchecked")
	public boolean getBraByBdr(String bdrId, String bdrType){
		boolean isUsed = false;
		List list = new ArrayList();
		String hql = "";
		
		try {
			hql = SQL_FROM + BaseReceiveAddress.REF + SQL_WHERE + "1 = 1";
			
			if ("0".equals(bdrType)) {
				hql += SQL_AND + "braCountry = ?";
			}else if ("1".equals(bdrType)){
				hql += SQL_AND + "braProvince = ?";
			}else if ("2".equals(bdrType)){
				hql += SQL_AND + "braCity = ?";
			}else if ("3".equals(bdrType)){
				hql += SQL_AND + "braDistrict = ?";
			}
			
			list = this.baseDao.find(hql, new Object[]{bdrId});
			
			if(list != null && !list.isEmpty()){
				isUsed = true;
			}else{
				hql = SQL_FROM + BaseDistributeRegion.REF + SQL_WHERE + "bdrParent = ?";
				list = this.baseDao.find(hql, new Object[]{bdrId});
				
				if(list != null && !list.isEmpty()){
					for (int i = 0; i < list.size(); i++) {
						BaseDistributeRegion bdr = (BaseDistributeRegion)list.get(i);
						isUsed = getBraByBdr(bdr.getBdrId(), bdr.getBdrType().toString());
						if (isUsed) break;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return isUsed;
	}

}
